package com.lry.basic.juc;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.LongAdder;

public class TestLongAddr {
    public static void main(String[] args) throws InterruptedException {
//        LongAdder longAdder = new LongAdder();
//        longAdder.increment();
//        longAdder.increment();
//        System.out.println(longAdder.longValue());
        longAdder();
//        testAI();
    }


    public static void testAI() throws InterruptedException {
        AtomicInteger ai = new AtomicInteger();

        List<Thread> threads = new ArrayList<>();
        int concurrent = 10;
        CountDownLatch latch = new CountDownLatch(concurrent);


        for(int i=0;i<concurrent;++i){
            Thread t  = new Thread(new Runnable() {
                @Override
                public void run() {

                    for(int i=0;i<100000;i++){
                        ai.incrementAndGet();
                    }
                    latch.countDown();
                }
            });
            threads.add(t);
        }

        long startTime = System.currentTimeMillis();
        threads.parallelStream().forEach(Thread::start);

        latch.await();
        System.out.println("AtomicInteger="+ai.intValue());

        System.out.println("AtomicInteger cost="+(System.currentTimeMillis()-startTime));

    }

    public static void longAdder() throws InterruptedException {
        LongAdder longAdder = new LongAdder();

        List<Thread> threads = new ArrayList<>();
        int concurrent = 10;
        CountDownLatch latch = new CountDownLatch(concurrent);


        for(int i=0;i<concurrent;++i){
            Thread t  = new Thread(new Runnable() {
                @Override
                public void run() {

                    for(int i=0;i<100000;i++){
                        longAdder.increment();
                    }
                    latch.countDown();
                }
            });
            threads.add(t);
        }

        long startTime = System.currentTimeMillis();
        threads.parallelStream().forEach(Thread::start);

        latch.await();
        System.out.println("longAdder="+longAdder.longValue());

        System.out.println("longAdder cost="+(System.currentTimeMillis()-startTime));

    }
}
